<template>
  <div class="home-page">
    <!-- 顶部搜索和Banner -->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">发现理想工作，开启职业新篇章</h1>
        <p class="hero-subtitle">求职招聘网站 - 连接人才与机会的桥梁</p>
        
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="输入职位名称、技能或公司名称"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
          
          <el-button type="primary" @click="handleSearch" class="search-button">
            <el-icon><search /></el-icon>
            搜索
          </el-button>
        </div>
        
        <div class="quick-tags">
          <span class="tags-label">热门搜索：</span>
          <el-tag 
            v-for="tag in hotSearchTags" 
            :key="tag"
            @click="quickSearch(tag)"
            class="quick-tag"
            effect="light"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
      
      <div class="hero-overlay"></div>
    </div>

    <!-- 数据统计 -->
    <div class="stats-section">
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-icon"><el-icon><user /></el-icon></div>
          <div class="stat-value">{{ statistics.userCount }}</div>
          <div class="stat-label">累计求职者</div>
        </div>
        <div class="stat-item">
          <div class="stat-icon"><el-icon><office-building /></el-icon></div>
          <div class="stat-value">{{ statistics.companyCount }}</div>
          <div class="stat-label">招聘企业</div>
        </div>
        <div class="stat-item">
          <div class="stat-icon"><el-icon><briefcase /></el-icon></div>
          <div class="stat-value">{{ statistics.jobCount }}</div>
          <div class="stat-label">在招职位</div>
        </div>
        <div class="stat-item">
          <div class="stat-icon"><el-icon><data-analysis /></el-icon></div>
          <div class="stat-value">{{ statistics.applyRate }}</div>
          <div class="stat-label">简历投递率</div>
        </div>
      </div>
    </div>

   

    <!-- 注册号召 -->
    <div class="cta-section">
      <div class="cta-container">
        <div class="cta-content">
          <h2 class="cta-title">立即注册，发现更多职业机会</h2>
          <p class="cta-text">完善个人信息，上传简历，开启您的职业之旅</p>
          
          <div class="cta-buttons">
            <el-button 
              type="primary" 
              size="large" 
              @click="register" 
              class="cta-button"
              :loading="loadingRegister"
            >
              立即注册
            </el-button>
            <el-button 
              plain 
              size="large" 
              @click="employerRegister" 
              class="cta-button"
              :loading="loadingEmployerRegister"
            >
              我是企业招聘者
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Right, 
  Calendar, 
  Location,
  User,
  OfficeBuilding,
  Briefcase,
  DataAnalysis,
  View,
  Clock
} from '@element-plus/icons-vue'
import { getJobs, searchJobs } from '@/api/job'
import { getJobFairs, checkUserRegistered, checkCompanyRegistered } from '@/api/jobfair'
import { getCareerGuides } from '@/api/forum'
import { getUserInfo } from '@/api/auth'

const router = useRouter()
const route = useRoute()
const searchKeyword = ref('')
const userRole = ref(null) // 用户角色

// 添加一个标志变量来跟踪组件是否已经卸载
const isComponentUnmounted = ref(false)

// 热门搜索标签
const hotSearchTags = [
  '前端开发',
  'Java工程师',
  '产品经理',
  'UI设计师',
  '数据分析',
  '人工智能'
]

// 统计数据
const statistics = ref({
  userCount: 0,
  companyCount: 0,
  jobCount: 0,
  applyRate: 0
})

// 特色职位
const featuredJobs = ref([])

// 推荐职位
const recommendedJobs = ref([])

// 招聘会
const jobFairs = ref([])

// 求职指南
const careerGuides = ref([])

// 数据加载状态
const loadingJobs = ref(false)
const loadingJobFairs = ref(false)
const loadingRegister = ref(false)
const loadingEmployerRegister = ref(false)

// 获取招聘会状态文本
const getFairStatusText = (status) => {
  switch (status) {
    default:
      return '欢迎参加';
  }
}

// 将招聘会状态转换为前端所需的status值
const convertFairStatus = (status) => {
  switch (status) {
    case 0: return 'upcoming';
    case 1: return 'ongoing';
    case 2: return 'ended';
    case 3: return 'canceled';
    default: return 'unknown';
  }
}

// 初始化数据
onMounted(() => {
  isComponentUnmounted.value = false
  
  // 先加载模拟数据，确保有内容显示
  initializeWithMockData()
  
  // 然后再加载真实数据
  loadFeaturedJobs()
  loadRecommendedJobs()
  loadJobFairs()
  loadStatistics()
  loadCareerGuides()
})

// 使用模拟数据初始化
const initializeWithMockData = () => {
  // 热门职位模拟数据
  featuredJobs.value = [
  {
    id: 1,
    title: '高级前端开发工程师',
    companyName: '字节跳动',
    companyLogo: '',
    city: '北京',
    experience: '3-5年',
    education: '本科',
    salary: '25-35k·13薪',
    highlights: ['团队氛围好', '技术氛围浓厚', '五险一金', '年终奖', '定期团建']
  },
  {
    id: 2,
    title: 'Java高级开发工程师',
    companyName: '阿里巴巴',
    companyLogo: '',
    city: '杭州',
    experience: '5-10年',
    education: '本科',
    salary: '35-50k·16薪',
    highlights: ['弹性工作', '股票期权', '免费三餐', '定期体检', '带薪年假']
  },
  {
    id: 3,
    title: '产品经理（数据方向）',
    companyName: '腾讯科技',
    companyLogo: '',
    city: '深圳',
    experience: '3-5年',
    education: '本科',
    salary: '25-40k·14薪',
    highlights: ['发展空间大', '领导好', '扁平管理', '双休', '加班少']
  }
]

  // 推荐职位模拟数据
  recommendedJobs.value = [
  {
    id: 4,
    title: 'UI设计师',
    companyName: '网易游戏',
    city: '广州',
    experience: '1-3年',
    education: '本科',
    salary: '12-20k'
  },
  {
    id: 5,
    title: '数据分析师',
    companyName: '京东科技',
    city: '北京',
    experience: '3-5年',
    education: '硕士',
    salary: '18-30k'
  },
  {
    id: 6,
    title: '运营专员',
    companyName: '小红书',
    city: '上海',
    experience: '1-3年',
    education: '本科',
    salary: '10-15k'
  },
  {
    id: 7,
    title: 'Android开发工程师',
    companyName: '百度',
    city: '北京',
    experience: '3-5年',
    education: '本科',
    salary: '25-35k'
  },
  {
    id: 8,
    title: '算法工程师',
    companyName: '华为',
    city: '深圳',
    experience: '3-5年',
    education: '硕士',
    salary: '30-45k'
  },
  {
    id: 9,
    title: 'HR经理',
    companyName: '美团',
    city: '北京',
    experience: '5-10年',
    education: '本科',
    salary: '25-35k'
  }
]

  // 招聘会模拟数据
  jobFairs.value = [
  {
    id: 1,
    title: '2025互联网科技人才招聘会',
    time: '2025-06-15 10:00-17:00',
    location: '北京国际会展中心',
    poster: 'https://img.yzcdn.cn/vant/cat.jpeg',
    status: 'upcoming',
    companies: [
      { name: '阿里巴巴', logo: '' },
      { name: '腾讯', logo: '' },
      { name: '字节跳动', logo: '' },
      { name: '百度', logo: '' },
      { name: '美团', logo: '' },
      { name: '京东', logo: '' },
      { name: '华为', logo: '' }
    ]
  },
  {
    id: 2,
    title: '金融行业春季招聘会',
    time: '2025-04-20 09:00-16:00',
    location: '上海世贸展览馆',
    poster: 'https://img.yzcdn.cn/vant/cat.jpeg',
    status: 'upcoming',
    companies: [
      { name: '中国银行', logo: '' },
      { name: '招商银行', logo: '' },
      { name: '平安保险', logo: '' },
      { name: '蚂蚁金服', logo: '' },
      { name: '国泰君安', logo: '' }
    ]
  },
  {
    id: 3,
    title: '2025应届生春季招聘会',
    time: '2025-03-25 09:30-17:00',
    location: '深圳会展中心',
    poster: 'https://img.yzcdn.cn/vant/cat.jpeg',
    status: 'ended',
    companies: [
      { name: '腾讯', logo: '' },
      { name: '华为', logo: '' },
      { name: '中兴', logo: '' },
      { name: 'OPPO', logo: '' },
      { name: 'vivo', logo: '' },
      { name: '小米', logo: '' }
    ]
  }
]

  // 统计数据
  statistics.value = {
    userCount: '1,598,532',
    companyCount: '84,279',
    jobCount: '215,632',
    applyRate: '92.7%'
  }
}

// 加载热门职位数据
const loadFeaturedJobs = async () => {
  if (isComponentUnmounted.value) return
  
  loadingJobs.value = true
  try {
    const res = await getJobs({ page: 1, size: 3, featured: true })
    
    // 检查组件是否已卸载
    if (isComponentUnmounted.value) return
    
    if (res.code === 200 && res.data && res.data.records && res.data.records.length > 0) {
      featuredJobs.value = res.data.records.map(job => ({
        id: job.id || 0,
        title: job.title || '职位名称',
        companyName: job.companyName || '公司名称',
        companyLogo: job.companyLogo || '',
        city: job.city || '未知',
        experience: job.experience || '经验不限',
        education: job.education || '学历不限',
        salary: job.salary || '薪资面议',
        highlights: job.benefits ? job.benefits.split(',') : []
      }))
    }
  } catch (error) {
    if (isComponentUnmounted.value) return
    console.error('获取热门职位失败:', error)
    // 已经在initializeWithMockData中初始化了数据，这里不需要再设置
  } finally {
    if (isComponentUnmounted.value) return
    loadingJobs.value = false
  }
}

// 加载推荐职位数据
const loadRecommendedJobs = async () => {
  if (isComponentUnmounted.value) return
  
  try {
    const res = await getJobs({ page: 1, size: 6 })
    
    // 检查组件是否已卸载
    if (isComponentUnmounted.value) return
    
    if (res.code === 200 && res.data && res.data.records && res.data.records.length > 0) {
      recommendedJobs.value = res.data.records.map(job => ({
        id: job.id || 0,
        title: job.title || '职位名称',
        companyName: job.companyName || '公司名称',
        city: job.city || '未知',
        experience: job.experience || '经验不限',
        education: job.education || '学历不限',
        salary: job.salary || '薪资面议'
      }))
    }
  } catch (error) {
    if (isComponentUnmounted.value) return
    console.error('获取推荐职位失败:', error)
    // 已经在initializeWithMockData中初始化了数据，这里不需要再设置
  }
}

// 加载招聘会数据
const loadJobFairs = async () => {
  if (isComponentUnmounted.value) return
  
  loadingJobFairs.value = true
  try {
    // 先获取用户信息（如果已登录）
    const token = localStorage.getItem('token')
    let companyIdToUse = null
    
    if (token) {
      try {
        console.log('首页 - 刷新招聘会前获取用户信息')
        
        const userResponse = await getUserInfo()
        if (userResponse && userResponse.data) {
          userRole.value = userResponse.data.role
          console.log('首页 - 获取到用户角色:', userRole.value, '类型:', typeof userRole.value)
          
          // 保存公司ID，如果存在
          if (userResponse.data.companyId) {
            companyIdToUse = userResponse.data.companyId
            console.log('首页 - 获取到企业ID:', companyIdToUse)
          } else if (userResponse.data.company && userResponse.data.company.id) {
            companyIdToUse = userResponse.data.company.id
            console.log('首页 - 从company对象获取到企业ID:', companyIdToUse)
          }
        }
      } catch (error) {
        console.error('首页 - 获取用户信息失败:', error)
      }
    }
    
    const res = await getJobFairs({ page: 1, size: 3 })
    
    // 检查组件是否已卸载
    if (isComponentUnmounted.value) return
    
    if (res.code === 200 && res.data && res.data.records && res.data.records.length > 0) {
      jobFairs.value = res.data.records.map(fair => {
        // 处理时间格式
        const startTime = fair.startTime ? new Date(fair.startTime) : new Date()
        const endTime = fair.endTime ? new Date(fair.endTime) : new Date()
        const timeStr = `${startTime.toLocaleDateString()} ${startTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}-${endTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}`
        
        // 映射参展企业数据
        const companies = []
        if (fair.companies && Array.isArray(fair.companies)) {
          fair.companies.forEach(company => {
            if (company && company.name) {
              companies.push({
                name: company.name,
                logo: company.logo || ''
              })
            }
          })
        }
        
        return {
          id: fair.id || 0,
          title: fair.title || '招聘会',
          time: timeStr,
          location: fair.typeName === '线上招聘会' ? '线上举办' : (fair.address || '地点待定'),
          poster: fair.poster || 'https://img.yzcdn.cn/vant/cat.jpeg',
          status: convertFairStatus(fair.status),
          isRegistered: false // 默认未报名
        }
      })
      
      // 如果用户已登录且有招聘会数据，直接使用已获取的用户角色和公司ID检查报名状态
      if (token && jobFairs.value.length > 0) {
        const isRecruiter = userRole.value === 1 || userRole.value === '1'
        
        // 检查报名状态
        if (isRecruiter && companyIdToUse) {
          console.log('首页 - 直接使用获取的企业ID检查报名状态:', companyIdToUse)
          await checkCompanyRegistrationStatus(companyIdToUse)
        } else {
          await checkUserRegistrationStatus()
        }
      }
    }
  } catch (error) {
    if (isComponentUnmounted.value) return
    console.error('获取招聘会失败:', error)
    // 已经在initializeWithMockData中初始化了数据，这里不需要再设置
  } finally {
    if (isComponentUnmounted.value) return
    loadingJobFairs.value = false
  }
}

// 检查企业报名状态
const checkCompanyRegistrationStatus = async (companyIdToUse) => {
  if (isComponentUnmounted.value || !companyIdToUse) return
  
  try {
    console.log('首页 - 开始检查企业报名状态')
    
    // 使用Promise.all并行请求所有招聘会的报名状态
    const checkPromises = jobFairs.value.map(fair => {
      console.log(`首页 - 检查企业报名状态 - 招聘会ID:${fair.id}, 企业ID:${companyIdToUse}`)
      return checkCompanyRegistered(fair.id, companyIdToUse)
        .then(response => {
          if (isComponentUnmounted.value) return fair
          
          if (response && response.data !== undefined) {
            console.log(`首页 - 企业报名状态结果 - 招聘会ID:${fair.id}`, response.data)
            fair.isRegistered = response.data
          }
          return fair
        })
        .catch(error => {
          if (isComponentUnmounted.value) return fair
          console.error(`首页 - 检查企业报名状态失败 - 招聘会ID:${fair.id}`, error)
          return fair
        })
    })
    
    await Promise.all(checkPromises)
  } catch (error) {
    if (isComponentUnmounted.value) return
    console.error('首页 - 检查企业报名状态失败', error)
  }
}

// 检查普通用户报名状态
const checkUserRegistrationStatus = async () => {
  if (isComponentUnmounted.value) return
  
  try {
    console.log('首页 - 开始检查普通用户报名状态')
    
    // 使用Promise.all并行请求所有招聘会的报名状态
    const checkPromises = jobFairs.value.map(fair => {
      return checkUserRegistered(fair.id)
        .then(response => {
          if (isComponentUnmounted.value) return fair
          
          if (response && response.data !== undefined) {
            console.log(`首页 - 用户报名状态结果 - 招聘会ID:${fair.id}`, response.data)
            fair.isRegistered = response.data
          }
          return fair
        })
        .catch(error => {
          if (isComponentUnmounted.value) return fair
          console.error(`首页 - 检查用户报名状态失败 - 招聘会ID:${fair.id}`, error)
          return fair
        })
    })
    
    await Promise.all(checkPromises)
  } catch (error) {
    if (isComponentUnmounted.value) return
    console.error('首页 - 检查普通用户报名状态失败', error)
  }
}

// 处理招聘会报名或查看
const handleRegisterFair = (fair) => {
  event.stopPropagation()
  
  // 添加日志，打印当前用户角色
  console.log('首页 - 当前用户角色:', userRole.value, '类型:', typeof userRole.value)
  console.log('首页 - 是否招聘者:', userRole.value === 1 || userRole.value === '1')
  
  // 如果已报名，直接提示并跳转
  if (fair.isRegistered) {
    ElMessage({
      message: '您已成功报名此招聘会',
      type: 'success',
      duration: 3000
    })
    viewJobFairDetail(fair.id)
    return
  }
  
  // 检查是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再报名招聘会')
    router.push({
      path: '/auth/login',
      query: { redirect: `/job-fairs/${fair.id}` }
    })
    return
  }
  
  // 根据用户角色和招聘会状态处理
  const isRecruiter = userRole.value === 1 || userRole.value === '1'
  
  if (fair.status === 'upcoming') {
    // 添加日志，表明当前操作
    console.log('首页 - 即将跳转到招聘会详情页', '用户角色:', isRecruiter ? '招聘者' : '普通用户')
    
    // 跳转到详情页前告知用户
    if (isRecruiter) {
      ElMessage.info('即将跳转到详情页，您可以在详情页为企业完成报名')
    } else {
      ElMessage.info('即将跳转到详情页，您可以在详情页完成报名')
    }
    
    // 跳转到详情页
    viewJobFairDetail(fair.id)
    return
  }
  
  // 查看招聘会详情
  viewJobFairDetail(fair.id)
}

// 加载统计数据
const loadStatistics = () => {
  if (isComponentUnmounted.value) return
  
  // 这里可以添加真实的统计数据API调用
  // 暂时使用静态数据
  statistics.value = {
    userCount: '1,598,532',
    companyCount: '84,279',
    jobCount: '215,632',
    applyRate: '92.7%'
  }
}

// 加载求职指南数据
const loadCareerGuides = async () => {
  if (isComponentUnmounted.value) return
  
  try {
    const res = await getCareerGuides({ page: 1, size: 3 })
    
    // 检查组件是否已卸载
    if (isComponentUnmounted.value) return
    
    if (res.code === 200 && res.data && res.data.records && res.data.records.length > 0) {
      careerGuides.value = res.data.records.map(guide => ({
        id: guide.id || 0,
        title: guide.title || '指南标题',
        category: guide.boardName || '职业指导',
        summary: guide.summary || guide.content?.substring(0, 100) || '暂无描述',
        cover: guide.cover || 'https://img.yzcdn.cn/vant/cat.jpeg',
        viewCount: guide.views || 0,
        publishTime: formatDate(guide.createTime) || '刚刚'
      }))
    } else {
      // 如果没有数据，显示默认内容
      careerGuides.value = [
  {
    id: 1,
    title: '如何准备技术面试：程序员必备指南',
    category: '面试技巧',
    summary: '本文将从技术准备、项目经验梳理、行为面试等方面，为程序员提供全方位的面试准备指南。',
    cover: 'https://img.yzcdn.cn/vant/cat.jpeg',
    viewCount: 15243,
    publishTime: '2025-01-15'
  },
  {
    id: 2,
    title: '2025年最受欢迎的职业技能与发展方向',
    category: '职业规划',
    summary: '基于最新的行业数据，分析2025年最有前景的职业发展方向，并提供相应的技能提升建议。',
    cover: 'https://img.yzcdn.cn/vant/cat.jpeg',
    viewCount: 9876,
    publishTime: '2025-02-10'
  },
  {
    id: 3,
    title: '简历优化指南：如何让HR在5秒内决定约你面试',
    category: '简历技巧',
    summary: '详细介绍如何打造一份能够抓住HR眼球的简历，包括内容组织、关键词优化、排版技巧等方面的建议。',
    cover: 'https://img.yzcdn.cn/vant/cat.jpeg',
    viewCount: 12568,
    publishTime: '2025-02-28'
  }
]
      console.log('没有找到求职指南数据，使用默认数据')
    }
  } catch (error) {
    if (isComponentUnmounted.value) return
    console.error('获取求职指南失败:', error)
    // 使用默认数据
    careerGuides.value = [
      {
        id: 1,
        title: '如何准备技术面试：程序员必备指南',
        category: '面试技巧',
        summary: '本文将从技术准备、项目经验梳理、行为面试等方面，为程序员提供全方位的面试准备指南。',
        cover: 'https://img.yzcdn.cn/vant/cat.jpeg',
        viewCount: 15243,
        publishTime: '2025-01-15'
      },
      {
        id: 2,
        title: '2025年最受欢迎的职业技能与发展方向',
        category: '职业规划',
        summary: '基于最新的行业数据，分析2025年最有前景的职业发展方向，并提供相应的技能提升建议。',
        cover: 'https://img.yzcdn.cn/vant/cat.jpeg',
        viewCount: 9876,
        publishTime: '2025-02-10'
      },
      {
        id: 3,
        title: '简历优化指南：如何让HR在5秒内决定约你面试',
        category: '简历技巧',
        summary: '详细介绍如何打造一份能够抓住HR眼球的简历，包括内容组织、关键词优化、排版技巧等方面的建议。',
        cover: 'https://img.yzcdn.cn/vant/cat.jpeg',
        viewCount: 12568,
        publishTime: '2025-02-28'
      }
    ]
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未知日期'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  router.push({
    path: '/jobs',
    query: { keyword: searchKeyword.value }
  })
}

// 快速搜索
const quickSearch = (tag) => {
  searchKeyword.value = tag
  handleSearch()
}

// 查看所有职位
const viewAllJobs = () => {
  router.push('/jobs')
}

// 查看职位详情
const viewJobDetail = (id) => {
  router.push(`/jobs/${id}`)
}

// 申请职位
const applyJob = (id) => {
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再申请职位')
    router.push({
      path: '/auth/login',
      query: { redirect: `/jobs/${id}` }
    })
    return
  }
  
  router.push(`/jobs/${id}`)
}

// 查看所有招聘会
const viewAllJobFairs = () => {
  router.push('/job-fairs')
}

// 查看招聘会详情
const viewJobFairDetail = (id) => {
  if (isComponentUnmounted.value) return
  
  // 防止id为undefined或null
  if (!id) {
    ElMessage.warning('招聘会信息不完整，无法查看详情')
    return
  }
  
  router.push(`/job-fairs/${id}`)
}

// 查看所有指南
const viewAllGuides = () => {
  router.push('/forum')
}

// 查看指南详情
const viewGuideDetail = (id) => {
  if (isComponentUnmounted.value) return
  
  // 防止id为undefined或null
  if (!id) {
    ElMessage.warning('指南信息不完整，无法查看详情')
    return
  }
  
  try {
  router.push(`/forum/topics/${id}`)
  } catch (error) {
    console.error('路由导航错误:', error)
    ElMessage.error('该页面暂未实现')
  }
}

// 注册
const register = () => {
  console.log('注册按钮被点击')
  
  // 清除所有登录状态
  logout()
  
  // 用户未登录，正常跳转到注册页面
  setTimeout(() => {
    window.location.href = window.location.origin + '/auth/register'
  }, 500)
}

// 企业注册
const employerRegister = () => {
  console.log('企业招聘者按钮被点击')
  
  // 清除所有登录状态
  logout()
  
  // 用户未登录，正常跳转到注册页面
  setTimeout(() => {
    window.location.href = window.location.origin + '/auth/register?type=employer'
  }, 500)
}

// 完全登出
const logout = () => {
  console.log('执行完全登出')
  // 清除所有与登录相关的状态
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  // 清除可能存在的其他用户相关数据
  sessionStorage.clear()
  // 清除所有cookie
  document.cookie.split(";").forEach(function(c) {
    document.cookie = c.replace(/^ +/, "")
      .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
  })
  
  ElMessage.success('已清除登录状态，即将前往注册页面')
}

// 监听路由变化
watch(() => route.path, (newPath, oldPath) => {
  console.log('首页 - 检测到路由变化:', oldPath, '->', newPath);
  
  // 当用户从其他页面导航回首页
  if (newPath === '/' && oldPath && oldPath !== '/') {
    console.log('首页 - 用户从', oldPath, '返回首页，重新获取招聘会数据');
    
    // 只重新加载招聘会数据
    loadJobFairs();
  }
}, { immediate: true });
</script>

<style>
.home-page {
  --primary-color: #1976d2;
  --secondary-color: #7c32a1;
  --accent-color: #ff6b00;
  --text-primary: #333333;
  --text-secondary: #666666;
  --text-light: #999999;
  --border-radius: 8px;
  --box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  --card-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
  --border-color: #eaeaea;
  --bg-light: #f8f9fa;
  --salary-color: #ff6b00;
  --highlight-color: #ebf8f2;
  --highlight-border: #e0f2e9;
  --highlight-text: #00b38a;
}

/* 顶部搜索和Banner */
.hero-section {
  position: relative;
  height: 550px;
  background: linear-gradient(135deg, #4a71ba, #7c32a1);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 0 1rem;
  overflow: hidden;
}

.hero-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url('https://img.yzcdn.cn/vant/cat.jpeg');
  background-size: cover;
  background-position: center;
  opacity: 0.1;
  z-index: 1;
}

.hero-content {
  max-width: 800px;
  margin: 0 auto;
  position: relative;
  z-index: 2;
}

.hero-title {
  font-size: 3rem;
  font-weight: 800;
  margin-bottom: 1.5rem;
  letter-spacing: -0.5px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.hero-subtitle {
  font-size: 1.4rem;
  margin-bottom: 2.5rem;
  opacity: 0.9;
  font-weight: 400;
}

.search-box {
  display: flex;
  margin-bottom: 1.5rem;
  max-width: 700px;
  margin-left: auto;
  margin-right: auto;
  height: 56px;
  border-radius: 28px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.search-box .el-input__wrapper {
  border-radius: 0;
  box-shadow: none !important;
  padding: 0 20px;
}

.search-box .el-input__inner {
  height: 56px;
  font-size: 1.1rem;
}

.search-button {
  border-radius: 0;
  font-size: 1.1rem;
  font-weight: 600;
  padding: 0 24px;
  height: 56px;
}

.quick-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  margin-top: 1.5rem;
}

.tags-label {
  margin-right: 0.8rem;
  font-size: 1rem;
  opacity: 0.9;
}

.quick-tag {
  margin: 0 0.3rem 0.5rem 0;
  cursor: pointer;
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  padding: 6px 16px;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.quick-tag:hover {
  background-color: rgba(255, 255, 255, 0.4);
  transform: translateY(-2px);
}

/* 数据统计 */
.stats-section {
  background-color: white;
  padding: 1.5rem 0;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 3rem;
  transform: translateY(-30px);
  border-radius: 12px;
  max-width: 100%;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  z-index: 10;
  overflow: hidden;
}

.stats-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
}

.stats-container {
  display: flex;
  justify-content: space-around;
  padding: 0 1rem;
  max-width: 1400px;
  width: 100%;
  margin: 0 auto;
}

.stat-item {
  text-align: center;
  flex: 1;
  padding: 1.5rem 1rem;
  position: relative;
  min-width: 200px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-5px);
}

.stat-item:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 15%;
  height: 70%;
  width: 1px;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.03), rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.03));
}

.stat-icon {
  font-size: 2.2rem;
  color: var(--primary-color);
  margin-bottom: 0.8rem;
  background: rgba(25, 118, 210, 0.1);
  width: 60px;
  height: 60px;
  line-height: 60px;
  border-radius: 50%;
  margin: 0 auto 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-value {
  font-size: 2.5rem;
  font-weight: 800;
  color: var(--primary-color);
  margin-bottom: 0.7rem;
  line-height: 1;
  background: linear-gradient(90deg, #1976d2, #4a71ba);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.stat-label {
  color: var(--text-secondary);
  font-size: 1.1rem;
  font-weight: 500;
  opacity: 0.8;
}

/* 部分通用样式 */
.section {
  max-width: 1200px;
  width: 100%;
  margin: 0 auto 5rem;
  padding: 0 1rem;
  box-sizing: border-box;
}

.hot-jobs-section {
  padding: var(--spacing-xl) 0;
  background: var(--color-white);

  .section-header {
    max-width: var(--container-max-width);
    margin: 0 auto var(--spacing-xl);
    padding: 0 var(--spacing-lg);
    display: flex;
    justify-content: space-between;
    align-items: flex-end;

    .section-title-container {
      .section-title {
        font-size: var(--font-size-2xl);
        font-weight: 600;
        color: var(--text-primary);
        margin: 0 0 var(--spacing-xs);
      }

      .section-subtitle {
        color: var(--text-secondary);
        font-size: var(--font-size-md);
      }
    }

    .view-more-btn {
      font-size: var(--font-size-md);
      .el-icon {
        margin-left: var(--spacing-xs);
      }
    }
  }

  .job-carousel {
    max-width: var(--container-max-width);
    margin: 0 auto var(--spacing-xl);
    padding: 0 var(--spacing-lg);

    :deep(.el-carousel__container) {
      height: 480px !important;
    }

    :deep(.el-carousel__item) {
      border-radius: var(--border-radius-lg);
      overflow: hidden;

      &:not(.is-active) {
        .featured-job-card {
          transform: scale(0.85);
          opacity: 0.2;
          filter: blur(2px);
        }
      }

      &.is-active {
        .featured-job-card {
          transform: scale(1);
          opacity: 1;
          filter: blur(0);
        }
      }
    }

    .featured-job-card {
      height: 100%;
      background: var(--color-white);
      border-radius: var(--border-radius-lg);
      box-shadow: var(--box-shadow-lg);
      padding: var(--spacing-xl);
      display: flex;
      flex-direction: column;
      transition: all 0.5s ease;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.1);

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 200px;
        background: linear-gradient(135deg, var(--color-primary-light) 0%, var(--color-primary) 100%);
        opacity: 0.1;
        z-index: 0;
      }

      .job-card-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: var(--spacing-lg);
        position: relative;
        z-index: 1;

        .company-logo {
          width: 60px;
          height: 60px;
          border-radius: var(--border-radius-lg);
          overflow: hidden;
          background: var(--color-white);
          box-shadow: var(--box-shadow);
          display: flex;
          align-items: center;
          justify-content: center;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .logo-placeholder {
            width: 100%;
            height: 100%;
            background: var(--color-primary);
            color: var(--color-white);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: var(--font-size-xl);
            font-weight: 600;
          }
        }

        .job-salary {
          font-size: var(--font-size-lg);
          font-weight: 600;
          color: var(--color-success);
          background: var(--color-success-light);
          padding: var(--spacing-sm) var(--spacing-md);
          border-radius: var(--border-radius-full);
        }
      }

      .job-info {
        margin-bottom: var(--spacing-lg);
        position: relative;
        z-index: 1;

        .job-title {
          font-size: var(--font-size-xl);
          font-weight: 600;
          color: var(--text-primary);
          margin: 0 0 var(--spacing-sm);
          line-height: 1.4;
        }

        .company-name {
          font-size: var(--font-size-lg);
          color: var(--text-secondary);
          margin-bottom: var(--spacing-md);
        }

        .job-tags {
          display: flex;
          gap: var(--spacing-sm);
          margin-bottom: var(--spacing-lg);

          .el-tag {
            padding: var(--spacing-xs) var(--spacing-sm);
            font-size: var(--font-size-sm);
            border-radius: var(--border-radius-sm);
          }
        }
      }

      .job-highlights {
        flex: 1;
        position: relative;
        z-index: 1;

        .highlight-title {
          font-size: var(--font-size-md);
          font-weight: 500;
          color: var(--text-primary);
          margin-bottom: var(--spacing-sm);
        }

        .highlight-tags {
          display: flex;
          flex-wrap: wrap;
          gap: var(--spacing-sm);

          .highlight-tag {
            padding: var(--spacing-xs) var(--spacing-sm);
            font-size: var(--font-size-sm);
            border-radius: var(--border-radius-sm);
            background: var(--color-success-lighter);
            border: none;
            color: var(--color-success);
          }
        }
      }

      .apply-btn {
        width: 100%;
        height: 48px;
        font-size: var(--font-size-md);
        font-weight: 500;
        margin-top: var(--spacing-lg);
        position: relative;
        z-index: 1;

        &:hover {
          transform: translateY(-2px);
        }
      }
    }
  }

  .job-list {
    max-width: var(--container-max-width);
    margin: 0 auto;
    padding: 0 var(--spacing-lg);
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: var(--spacing-lg);

    .job-item {
      background: var(--color-white);
      border-radius: var(--border-radius-lg);
      padding: var(--spacing-lg);
      border: 1px solid var(--border-color);
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-4px);
        box-shadow: var(--box-shadow);
      }

      .job-card-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: var(--spacing-md);

        .job-item-company-info {
          display: flex;
          align-items: center;
          gap: var(--spacing-md);

          .job-company-logo {
            width: 48px;
            height: 48px;
            border-radius: var(--border-radius-md);
            overflow: hidden;

            .logo-placeholder {
              width: 100%;
              height: 100%;
              background: var(--color-primary);
              color: var(--color-white);
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: var(--font-size-lg);
              font-weight: 600;
            }
          }

          .job-company-details {
            .job-item-company {
              font-size: var(--font-size-md);
              color: var(--text-secondary);
            }
          }
        }

        .job-item-salary {
          font-size: var(--font-size-lg);
          font-weight: 600;
          color: var(--color-success);
        }
      }

      .job-item-content {
        .job-item-title {
          font-size: var(--font-size-lg);
          font-weight: 600;
          color: var(--text-primary);
          margin: 0 0 var(--spacing-sm);
        }

        .job-item-tags {
          display: flex;
          gap: var(--spacing-sm);
          margin-bottom: var(--spacing-md);

          .el-tag {
            padding: var(--spacing-xs) var(--spacing-sm);
            font-size: var(--font-size-sm);
          }
        }
      }

      .apply-now-btn {
        width: 100%;
        margin-top: var(--spacing-sm);
      }
    }
  }
}

@media (max-width: 1200px) {
  .section.hot-jobs-section {
    .job-list {
      grid-template-columns: 1fr;
    }
  }
}

@media (max-width: 768px) {
  .section.hot-jobs-section {
    padding: var(--spacing-lg) 0;

    .section-header {
      flex-direction: column;
      align-items: flex-start;
      gap: var(--spacing-sm);
      margin-bottom: var(--spacing-lg);

      .section-title {
        font-size: var(--font-size-xl);
      }
    }

    .job-carousel {
      :deep(.el-carousel__container) {
        height: 420px !important;
      }

      .featured-job-card {
        padding: var(--spacing-lg);

        .job-card-header {
          .company-logo {
            width: 60px;
            height: 60px;
          }

          .job-salary {
            font-size: var(--font-size-lg);
          }
        }

        .job-title {
          font-size: var(--font-size-lg);
        }

        .company-name {
          font-size: var(--font-size-md);
        }
      }
    }

    .job-list {
      gap: var(--spacing-md);

      .job-item {
        padding: var(--spacing-md);
      }
    }
  }
}

/* 招聘会部分 */
.job-fair-section {
  padding-bottom: 1rem;
}

.job-fair-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
}

.job-fair-card {
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.job-fair-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--card-shadow);
}

.fair-poster {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.fair-poster img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.6s ease;
}

.job-fair-card:hover .fair-poster img {
  transform: scale(1.05);
}

.fair-status {
  position: absolute;
  top: 1rem;
  right: 1rem;
  padding: 0.4rem 0.8rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
  background-color: rgba(255, 255, 255, 0.9);
  color: var(--text-secondary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.fair-status.upcoming {
  background: linear-gradient(90deg, #4caf50, #8bc34a);
  color: white;
}

.fair-content {
  padding: 1.5rem;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.fair-title {
  font-size: 1.2rem;
  font-weight: 700;
  margin-bottom: 1rem;
  color: var(--text-primary);
  line-height: 1.4;
}

.fair-meta {
  margin-bottom: 1.25rem;
}

.meta-item {
  display: flex;
  align-items: center;
  color: var(--text-secondary);
  font-size: 0.95rem;
  margin-bottom: 0.8rem;
}

.meta-item .el-icon {
  margin-right: 0.5rem;
  font-size: 1.1rem;
  color: var(--primary-color);
}

.fair-companies {
  margin-bottom: 1.5rem;
}

.companies-title {
  font-size: 0.95rem;
  font-weight: 600;
  margin-bottom: 0.8rem;
  color: var(--text-primary);
}

.companies-logos {
  display: flex;
  align-items: center;
}

.company-logo-small {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: -10px;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.company-logo-small img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.logo-text {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  font-weight: 600;
  color: white;
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
}

.company-more {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 2px solid white;
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  font-weight: 600;
  color: var(--text-secondary);
}

.register-btn {
  margin-top: auto;
  width: 100%;
}

/* 求职指南部分 */
.guide-section {
  padding-bottom: 1rem;
}

.guide-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
}

.guide-card {
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.guide-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--card-shadow);
}

.guide-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.guide-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.6s ease;
}

.guide-card:hover .guide-image img {
  transform: scale(1.05);
}

.guide-category {
  position: absolute;
  top: 1rem;
  left: 1rem;
  padding: 0.4rem 0.8rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
}

.guide-content {
  padding: 1.5rem;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.guide-title {
  font-size: 1.2rem;
  font-weight: 700;
  margin-bottom: 0.8rem;
  color: var(--text-primary);
  line-height: 1.4;
}

.guide-summary {
  color: var(--text-secondary);
  font-size: 0.95rem;
  margin-bottom: 1.5rem;
  line-height: 1.6;
  flex: 1;
}

.guide-meta {
  display: flex;
  justify-content: space-between;
  color: var(--text-light);
  font-size: 0.85rem;
  border-top: 1px solid var(--border-color);
  padding-top: 1rem;
}

.guide-views, .guide-date {
  display: flex;
  align-items: center;
}

.guide-meta .el-icon {
  margin-right: 0.4rem;
}

/* 注册号召 */
.cta-section {
  background: linear-gradient(135deg, #4a71ba, #7c32a1);
  color: white;
  padding: 5rem 0;
  margin-bottom: 0;
  position: relative;
  overflow: hidden;
}

.cta-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
  position: relative;
  z-index: 2;
}

.cta-content {
  text-align: center;
  max-width: 800px;
  margin: 0 auto;
}

.cta-title {
  font-size: 2.5rem;
  font-weight: 800;
  margin-bottom: 1.5rem;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.cta-text {
  font-size: 1.2rem;
  margin-bottom: 2.5rem;
  opacity: 0.9;
}

.cta-buttons {
  display: flex;
  justify-content: center;
  gap: 1.5rem;
}

.cta-button {
  padding: 0 2.5rem;
  height: 50px;
  font-size: 1.1rem;
  font-weight: 600;
  border-radius: 25px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.cta-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
}

.cta-button:active {
  transform: translateY(1px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .job-list {
    grid-template-columns: repeat(2, 1fr);
    width: 100%;
  }
  
  .el-carousel {
    width: 100%;
  }
  
  .job-fair-list,
  .guide-list {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .hero-title {
    font-size: 2.5rem;
  }
}

@media (max-width: 768px) {
  .hero-section {
    height: auto;
    padding: 4rem 0;
  }
  
  .hero-title {
    font-size: 2rem;
  }
  
  .hero-subtitle {
    font-size: 1.1rem;
    margin-bottom: 2rem;
  }
  
  .search-box {
    flex-direction: column;
    height: auto;
    box-shadow: none;
  }
  
  .search-box .el-input__inner {
    height: 46px;
  }
  
  .search-button {
    height: 46px;
    border-radius: 23px;
    margin-top: 1rem;
  }
  
  .stats-container {
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex: 0 0 50%;
    margin-bottom: 1.5rem;
  }
  
  .stat-item:nth-child(2n)::after {
    display: none;
  }
  
  .section-header {
    flex-direction: column;
  }
  
  .view-more-btn {
    margin-top: 1rem;
    align-self: flex-start;
  }
  
  .job-list,
  .job-fair-list,
  .guide-list {
    grid-template-columns: 1fr;
  }
  
  .cta-title {
    font-size: 2rem;
  }
  
  .cta-text {
    font-size: 1rem;
  }
  
  .cta-buttons {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .hero-title {
    font-size: 1.8rem;
  }
  
  .section-title {
    font-size: 1.5rem;
  }
  
  .job-carousel .el-carousel {
    display: none;
  }
  
  /* 超小屏幕的数据统计样式 */
  .stats-section {
    transform: translateY(-15px);
    padding: 0.5rem 0;
  }
  
  .stat-item {
    flex: 0 0 100%;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }
  
  .stat-item:last-child {
    border-bottom: none;
  }
  
  .stat-item::after {
    display: none;
  }
}

.job-company-logo .logo-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: 700;
  color: white;
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
}

/* 应用按钮 */
.apply-now-btn {
  margin-top: auto;
  width: 100%;
  border-radius: 6px;
  height: 34px;
  font-size: 0.85rem;
  font-weight: 600;
  letter-spacing: 0.5px;
  background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
  border: none;
  position: relative;
  overflow: hidden;
}

.apply-now-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(25, 118, 210, 0.15);
}

.apply-now-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: all 0.6s ease;
}

.apply-now-btn:hover::before {
  left: 100%;
}

:deep(.el-carousel--card) {
  .el-carousel__item {
    width: 60% !important;
  }
  
  .el-carousel__mask {
    opacity: 0;
  }
}
</style> 